package com.woniuxy.config;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rabbitmq.client.Channel;
import com.woniuxy.entity.AllRun;
import com.woniuxy.entity.DTO.GrabEvent;
import com.woniuxy.service.OrderRunService;
import com.woniuxy.service.RunService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class RunListener {
    @Autowired
    private RunService runService;
    @Autowired
    private OrderRunService orderRunService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @RabbitHandler
    @RabbitListener(queues = "runQueue2")
    public void handleGrabEvent(GrabEvent event, Channel channel, @Header(AmqpHeaders.MESSAGE_ID) String msgId,
                                @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        // 1. 幂等检查（防止重复消费）
        if (redisTemplate.opsForValue().get("grab:msg:" + msgId) != null) {
            try {
                channel.basicAck(deliveryTag, false); // 确认已处理过的消息
                return;
            } catch (IOException e) {
                log.error("确认消息失败", e);
            }
        }

        try {
            // 2. 创建订单（本地事务）
            orderRunService.createOrder(event);
            //修改跑腿帖子状态
            UpdateWrapper<AllRun> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("run_number", event.getTaskId());
            AllRun updateRun = new AllRun();
            updateRun.setState(1); // 设置状态为1
            updateRun.setTakeUserId(event.getUserId());
            boolean result = runService.update(updateRun, updateWrapper);
            System.out.println(result);
            // 3. 记录消息消费
            redisTemplate.opsForValue().set("grab:msg:" + msgId, "PROCESSED", 2, TimeUnit.HOURS);
            //4.删除库存
            redisTemplate.delete("stock:"+event.getTaskId());
// 手动确认消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            try {
                // 拒绝消息，根据业务需求决定是否重新入队
                channel.basicReject(deliveryTag, false); // false表示不重新入队
                log.error("抢单处理失败，已拒绝消息 task:{}, user:{}", event.getTaskId(), event.getUserId(), e);
            } catch (IOException ioException) {
                log.error("拒绝消息失败", ioException);
            }
        }
    }
}
